import CryptoJS from './crypto-js/crypto-js'
import qs1 from "qs";

// 默认的 KEY 与 iv 如果没有给
const KEY = CryptoJS.enc.Utf8.parse("KLF7KGtS9eZx7DWQ");
const IV = CryptoJS.enc.Utf8.parse('SRl2wsWc9OV3zzch');
var isDebug = false;
/**
 * AES加密 ：字符串 key iv  返回base64
 */
export function Encrypt(word, keyStr) {
	let key = KEY
	let iv = IV

	if (keyStr) {
		key = CryptoJS.enc.Utf8.parse(keyStr);
		iv = CryptoJS.enc.Utf8.parse(keyStr);
	}

	let srcs = CryptoJS.enc.Utf8.parse(word);
	var encrypted = CryptoJS.AES.encrypt(srcs, key, {
		iv: IV,
		mode: CryptoJS.mode.CBC,
		padding: CryptoJS.pad.ZeroPadding
	})
	// console.log("-=-=-=-", encrypted.ciphertext)
	return CryptoJS.enc.Base64.stringify(encrypted.ciphertext);
}

/**
 * AES 解密 ：字符串 key iv  返回base64
 */
export function Decrypt(word, keyStr) {
	let key = KEY
	let iv = IV

	if (keyStr) {
		key = CryptoJS.enc.Utf8.parse(keyStr);
		iv = CryptoJS.enc.Utf8.parse(keyStr);
	}

	let base64 = CryptoJS.enc.Base64.parse(word);
	let src = CryptoJS.enc.Base64.stringify(base64);

	var decrypt = CryptoJS.AES.decrypt(src, key, {
		iv: IV,
		mode: CryptoJS.mode.CBC,
		padding: CryptoJS.pad.ZeroPadding
	});
	var decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
	return decryptedStr.toString();
}

export function stringifyEncrypt(data, keyStr, ivStr) {
	let datas = qs1.stringify(data);
	let data2 = Encrypt(datas, keyStr, ivStr);
	if (isDebug == false) {
		return {
			p: encodeURIComponent(data2)
		};
	} else {
		return data
	}

}
